<?php

namespace app\manage\controller;

use think\Request;
use app\common\model\Category as CategoryM;

class Category extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $list = CategoryM::field('*')->select();
        $count = count($list);
        $data = [
            'items' => $list ? Base::ListTree($list->toArray()) : [],
            'total' => $count
        ];
        return $this->result_json(null, 1, $data);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $category = new CategoryM();
        $data = $request->only(['name', 'banner', 'group', 'pid', 'sort', 'status']);

        // 是否对pid的有效性进行判断
        if ($category->save($data)) {
            return $this->result_json('create success', 1, ['id' => $category->id]);
        } else {
            return $this->result_json('db error', 101);
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {

    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        // 字段验证和合法性验证
        $data = $request->only(['name', 'banner', 'group', 'pid','sort', 'status']);
        $category = CategoryM::get($id);    // 是否只查询单个字段
        if ($category) {
            if ($category->save($data) !== false) {
                return $this->result_json('update success', 1);
            }
            return $this->result_json('db error', 101);
        } else {
            return $this->result_json('param error', 201);
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id, $flag = true)
    {
        $instance = CategoryM::where('id', $id)->find();
        if (!$instance) {
            return $this->result_json('param error', 201);
        }

        $instance->status = $flag === 'true' ? -1 : 1;
        // 执行删除操作
        if ($instance->save() === false) {
            return $this->result_json('param error', 201);
        }
        return $this->result_json('delete success', 0);
    }
}
